/**
 * Created by Aranld on 2017/5/11.
 */
let schedule = require('node-schedule');
let log = require('../util/log.js');
let save = require('./save.js');
let variable = require('../data/variable.js');
let gameData = require('../util/gameData.js');
let msg = require('../util/msg.js');
let rpc = require('../util/rpc.js');
let mem = require('../util/mem.js');
let util = require('../util/util.js');
let file = require('../util/file.js');

let cron = module.exports;

cron.init = function () {
    // 建立一个时间循环的默认规则
    //let rule = new schedule.RecurrenceRule();
    // 增加一个每秒执行的内容
    //let times = [];
    //for (let i = 1; i < 60; i++) {
    //    times.push(i);
    //}
    //rule.second = times;
    // 开始动作
    schedule.scheduleJob('* * * * * *', function () {
        deleteRoom();
    });

    schedule.scheduleJob('0 * * * * *', function () {
        addRecord();
    });

    schedule.scheduleJob('0 */5 * * * *', function () {
        syncRoom();
    });
};

function deleteRoom() {
    let now = Date.now();
    let gameDuration = (gameData.d.config.gameDuration * 1000);
    for (let i in mem.games) {
        let game = mem.games[i];
        if (now - game.createTime < gameDuration) {
            continue;
        }

        for (let j = 0; j < 3; j++) {
            if (!mem.gamePlayers[game.id[j]]) {
                continue;
            }

            if (!mem.gamePlayers[game.id[j]].robot) {
                if (game.ddz) {
                    let result = {
                        "winner": game.id[j],
                        "multiple": game.ddz.getMultiple(),
                        "baseScore": game.ddz.getBaseScore(),
                        "spring": 0,
                        "coinType": gameData.d.gameLv[game.lv].coinType,
                        "result": [0, 0, 0],
                        "ids": [game.id[0], game.id[1], game.id[2]]
                    };
                    msg.send(mem.gamePlayers[game.id[j]].cid, mem.gamePlayers[game.id[j]].uuid, 'gamePlayEnd', null);
                    msg.send(mem.gamePlayers[game.id[j]].cid, mem.gamePlayers[game.id[j]].uuid, 'gameOverStart', result);
                }
                save.clearGameId(game.id[j], mem.gamePlayers[game.id[j]].cid, mem.gamePlayers[game.id[j]].uuid);
            } else {
                save.clearRobot(game.id[j]);
            }
            delete mem.gamePlayers[game.id[j]];
        }
        if (game.ddz) {
            game.ddz.close();
            game.ddz = null;
        }
        delete mem.games[i];
        let param = {};
        param.gameId = i;
        rpc.dc.send('delGame', param);
        if (gameData.d.gameLv[game.lv].type == 'custom') {
            rpc.dc.send('delRecruit', param);
        }
        log.p('timeout kill room', i);
    }
}

function syncRoom() {
    let gameIds = Object.keys(mem.games);
    let param = {};
    param.gameIds = gameIds;
    param.serverId = util.getServerInfo('id');
    rpc.dc.send('syncGame', param);
}

function addRecord() {
    let play = JSON.stringify(mem.recordData.play);
    mem.recordData.play = {};
    let win = JSON.stringify(mem.recordData.win);
    mem.recordData.win = {};
    let addGold = JSON.stringify(mem.recordData.addGold);
    mem.recordData.addGold = {};

    let date = (new Date()).Format('hh:mm');
    let time = Math.floor(Date.now() / 1000);

    file.append(variable.path.play, date + "\t" + time + "\t" + play + "\n");
    file.append(variable.path.win, date + "\t" + time + "\t" + win + "\n");
    file.append(variable.path.addGold, date + "\t" + time + "\t" + addGold + "\n");
}